import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { User, UserDocument, UserSchema } from './schemas/user.schema';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UsersService {
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.findOne(username);
    if (user && await bcrypt.compare(password, user.password)) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }


  async create(username: string, password: string): Promise<User | {code: number, message: string, data: null}> {
    const existingUser = await this.userModel.findOne({ username })
    if (existingUser) {
      return {code: 400, message: '用户名已存在', data: null}
    }
    const hashedPassword = await bcrypt.hash(password, 10);
    const createdUser = new this.userModel({
      _id: new Types.ObjectId(), // 手动设置 _id
      username,
      password: hashedPassword,
      avatar: 'https://avatars.githubusercontent.com/u/102649980?v=4',
      certified_driver: false,
      score: new Date(),
      settledTime: new Date(),
      updateTime:new Date(),
    });
    return createdUser.save();
  }

  async newSignUp(
    username: string,
    password: string,
  ): Promise<User> {
    const hashedPassword = await bcrypt.hash(password, 10);
    const createdUser = new this.userModel({
      _id: new Types.ObjectId(), // 手动设置 _id
      username,
      password: hashedPassword,
      avatar: 'https://avatars.githubusercontent.com/u/102649980?v=4',
      certified_driver: false,
      score: new Date(),
      settledTime: new Date(),
      updateTime:new Date(),
    });
    return createdUser.save();
  }

  async findAll(): Promise<User[]> {
    return this.userModel.find().exec();
  }

  async findOne(username: string): Promise<User | undefined> {
    return this.userModel.findOne({ username }).exec();
  }

  async findOneByName(username: string): Promise<User | undefined> {
    const user = await this.userModel.findOne({username}).exec();
    return user;
  }

  async findOneById(id: string | number): Promise<User | undefined> {
    const objectId = new Types.ObjectId(id);
    const user = await this.userModel.findOne({_id: objectId}).exec();
    return user;
  }


}